#include "threadPool.h"
int exitPipe[2];
void sigFunc(int signum){
    printf("parent is going to exit!\n");
    write(exitPipe[1],"1",1);
}
int main(int argc, char *argv[])
{
    // ./sever 192.168.118.128 1234 3
    ARGS_CHECK(argc,4);
    pipe(exitPipe);
    if(fork() != 0){
        close(exitPipe[0]);
        signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }
    close(exitPipe[1]);
    int workerNum = atoi(argv[3]);
    threadPool_t threadPool;//这个数据结构里面包含了线程池运行的所有组件
    threadPool.tidArr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    threadPool.workerNum = workerNum;
    pthread_mutex_init(&threadPool.mutex,NULL);
    pthread_cond_init(&threadPool.cond,NULL);
    threadPool.exitflag = 0; //一开始是不需要退出的
    makeWorker(&threadPool);
    bzero(&threadPool.taskQueue,sizeof(queue_t));

    int sockfd;
    tcpInit(&sockfd,argv[1],argv[2]);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);
    while(1){
        struct epoll_event readySet[2];
        int readyNum = epoll_wait(epfd,readySet,2,-1);
        for(int i = 0; i < readyNum; ++i){
            if(readySet[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.mutex);
                Enqueue(&threadPool.taskQueue,netfd);
                printf("master send a task!\n");
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else if(readySet[i].data.fd == exitPipe[0]){
                printf("threadPool is going to exit!\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitflag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
                //for(int j = 0; j < workerNum; ++j){
                //    pthread_cancel(threadPool.tidArr[j]);
                //}

                for(int j = 0; j < workerNum; ++j){
                    pthread_join(threadPool.tidArr[j],NULL);
                }
                printf("all worker is exited!\n");
                pthread_exit(NULL);
            }
        }
    }
    return 0;
}

